package com.example.administrator.u17.activity;


import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.u17.R;
import com.example.administrator.u17.adapter.GameHeaderAdapter;
import com.example.administrator.u17.adapter.MineGameAdapter;
import com.example.administrator.u17.adapter.MineGameHeaderAdapter;
import com.example.administrator.u17.config.NetConfig;

import com.example.administrator.u17.db.MineGameDb;
import com.example.administrator.u17.model.MineGame;

import com.example.administrator.u17.model.MineGameHOTRecomment;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class GameActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private ImageView ivBack;
    private ViewPager viewPager;
    // TODO: 2016/11/15  ArrayList
    private ArrayList<MineGame.DataBean.ReturnDataBean.ItemListBean> mList;
    private MineGameAdapter mineGameAdapter;
    //Adapter ViewPager的适配器
    private MineGameHeaderAdapter mineGameHeaderAdapter;
    private LinearLayout linearLayout;
    private PullToRefreshListView pullToRefreshListView;
    private String path;
    private int currentPage = 1;
    private DbManager dbManager;
    private GameHeaderAdapter gameHeadAdapter;
    private ArrayList<MineGameHOTRecomment.DataBean.ReturnDataBean.GameheaderBean.RecommandsBean> mRecommentList;
    private GridView gridView;
    private ArrayList<View> mViewList;
    private ArrayList<ImageView> ivs;
    private Handler handler;
    private Timer timer;
    private int index;

    private ImageView iv1, iv2, iv3, iv4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_game);
        initView();
        initData();
        setData();
        setListener();
    }

    private void setListener() {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");

        ILoadingLayout proxy = pullToRefreshListView.getLoadingLayoutProxy();
        proxy.setRefreshingLabel("正在拼命加载中。。。");
        proxy.setLastUpdatedLabel("最后刷新时间" + sdf.format(c.getTime()));
    }

    private void setData() {

        pullToRefreshListView.setAdapter(mineGameAdapter);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                loadData(1);
                currentPage = 1;
                loadHotData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadData(currentPage);
                loadHotData();
            }
        });
    }

    public void loadData(int page) {
        path = NetConfig.GAME_PATH + page;
        x.http().get(new RequestParams(path), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                Log.e("TAG", "onSuccess: " + s);
                MineGameDb mDB = new MineGameDb();
                mDB.json = s;
                mDB.path = path;
                mDB.time = System.currentTimeMillis();
                try {
                    dbManager.save(mDB);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                MineGame mineG = new Gson().fromJson(s, MineGame.class);
                if (currentPage == 1) {
                    mList.clear();
                }
                currentPage++;
                mList.addAll(mineG.getData().getReturnData().getItemList());
                mineGameAdapter.notifyDataSetChanged();

                Log.e("TAG", "onPullUpToRefresh: " + currentPage);

            }

            @Override
            public void onError(Throwable throwable, boolean b) {

                try {
                    List<MineGameDb> list = dbManager.selector(MineGameDb.class).where("path", "=", path)
                            .findAll();
                    long duration = System.currentTimeMillis();
                    if (duration > 1000 * 60 * 30) {
                        dbManager.delete(MineGameDb.class, WhereBuilder.b("path", "=", path));
                    } else {
                        MineGameDb m = new MineGameDb();
                        m.json = list.get(0).json;
                        MineGame minG = new Gson().fromJson(m.json, MineGame.class);
                        mList.addAll(minG.getData().getReturnData().getItemList());
                        mineGameAdapter.notifyDataSetChanged();
                        pullToRefreshListView.onRefreshComplete();
                        return;
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

                pullToRefreshListView.onRefreshComplete();
            }
        });
    }

    private void initData() {

        dbManager = x.getDb(new DbManager.DaoConfig());
        try {
            dbManager.save(new MineGameDb());
        } catch (DbException e) {
            e.printStackTrace();
        }

        loadHotData();
        loadData(currentPage);
    }

    private void initView() {
        mList = new ArrayList<>();
        mineGameAdapter = new MineGameAdapter(mList, this);
        View view = View.inflate(this, R.layout.mine_game_header, null);
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.game_pullTo_shop_lv);

        linearLayout = (LinearLayout) view.findViewById(R.id.ll_mine_game_header);
        ivBack = (ImageView) findViewById(R.id.iv_mine_game_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        linearLayout = (LinearLayout) findViewById(R.id.ll_mine_game_header);
        viewPager = (ViewPager) view.findViewById(R.id.viewPager_mine_header);

        mRecommentList = new ArrayList<>();


        gameHeadAdapter = new GameHeaderAdapter(mRecommentList, this);
        gridView = (GridView) view.findViewById(R.id.gv_mine);
        gridView.setAdapter(gameHeadAdapter);
        pullToRefreshListView.getRefreshableView().addHeaderView(linearLayout);

        ivs = new ArrayList<>();
        View view1 = View.inflate(this, R.layout.mine_game_header, null);
        ivs.add((ImageView) view1.findViewById(R.id.iv_4));
        ivs.add((ImageView) view1.findViewById(R.id.iv_1));
        ivs.add((ImageView) view1.findViewById(R.id.iv_2));
        ivs.add((ImageView) view1.findViewById(R.id.iv_3));
        ivs.add((ImageView) view1.findViewById(R.id.iv_4));
        ivs.add((ImageView) view1.findViewById(R.id.iv_1));

        ivs.get(0).setSelected(true);
        View view2 = View.inflate(this, R.layout.view_1, null);
        iv1 = (ImageView) view2.findViewById(R.id.iv_view_1);
        View view3 = View.inflate(this, R.layout.view_2, null);
        iv2 = (ImageView) view3.findViewById(R.id.iv_view_2);
        View view4 = View.inflate(this, R.layout.view_3, null);
        iv3 = (ImageView) view4.findViewById(R.id.iv_view_3);
        View view5 = View.inflate(this, R.layout.view_4, null);
        iv4 = (ImageView) view5.findViewById(R.id.iv_view_4);

        mViewList = new ArrayList<>();
        mViewList.add(View.inflate(this, R.layout.view_1, null));
        mViewList.add(View.inflate(this, R.layout.view_2, null));
        mViewList.add(View.inflate(this, R.layout.view_3, null));
        mViewList.add(View.inflate(this, R.layout.view_4, null));

        mineGameHeaderAdapter = new MineGameHeaderAdapter(mViewList, this);
        viewPager.setAdapter(mineGameHeaderAdapter);
        viewPager.addOnPageChangeListener(this);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                viewPager.setCurrentItem(msg.arg1, true);

            }
        };
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {


                Message msg = Message.obtain();
                index++;
                msg.arg1 = index % 4 + 1;
                msg.what = 1001;
                handler.sendMessage(msg);

            }
        }, 1000, 3000);


    }

    public void loadHotData() {
        path = NetConfig.HOT_COMMENT;
        x.http().get(new RequestParams(path), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                MineGameHOTRecomment recomment = new Gson().fromJson(s, MineGameHOTRecomment.class);


                mRecommentList.addAll(recomment.getData().getReturnData().getGameheader().getRecommands());


                gameHeadAdapter.notifyDataSetChanged();

                x.image().bind(iv1, recomment.getData().getReturnData()
                        .getGameheader().getBanner().get(0).getCoverUrl());

                Picasso.with(GameActivity.this).load(recomment.getData().getReturnData()
                        .getGameheader().getBanner().get(1).getCoverUrl()).into(iv2);
                Picasso.with(GameActivity.this).load(recomment.getData().getReturnData()
                        .getGameheader().getBanner().get(2).getCoverUrl()).into(iv3);
                Picasso.with(GameActivity.this).load(recomment.getData().getReturnData()
                        .getGameheader().getBanner().get(3).getCoverUrl()).into(iv4);


            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {


        for (int i = 0; i < ivs.size(); i++) {

            if (i == position) {

                ivs.get(i).setImageResource(R.drawable.point_gray);
            } else {
                ivs.get(i).setImageResource(R.drawable.point_white);
            }
            ivs.get(i).setSelected(i == position);
        }

        currentPage = position;
        switch (position) {
            case 0:
            case 4:
                setSelect(3);
                break;
            case 2:
            case 5:
                setSelect(1);
                break;
            case 3:
                setSelect(2);
                break;
        }

    }

    private void setSelect(int index) {
        for (int i = 0; i < ivs.size(); i++) {
            ivs.get(i).setSelected(i == index);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {


        if (state == ViewPager.SCROLL_STATE_IDLE) {
            if (currentPage == 0) {
                viewPager.setCurrentItem(4, false);
            } else if (currentPage == 5) {

                viewPager.setCurrentItem(2, false);

            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewPager.removeOnPageChangeListener(GameActivity.this);
    }
}
